<template>
  <div class="form-container">
    <el-form
        :rules="rules"
        ref="ruleFormRef"
        :model="formProps.model"
        label-width="150px"
        label-position="right"
        class="demo-ruleForm"

    >
      <el-form-item :style="{ width: form.width + 'px' }" v-for="(form,index) in formProps.formItems" :key="index" :label="form.label" :prop="form.key">
        <template v-if="form.type === 'el-input'">
          <el-input :rows="form.rows" :type="form?.inputType"  size="large" v-model="formProps.model[form.key]" :placeholder="form.placeholder"/>
        </template>
        <template v-else-if="form.type === 'el-radio'">
          <el-radio v-for="(sex,index) in form.radioOptions" v-model="formProps.model[form.key]" :key="index" :label="sex.value" size="large">{{ sex.label }}</el-radio>
        </template>
<!--        自定义通用插槽-->
        <template v-else-if="form.isSlot">
          <slot :name="form.key"></slot>
        </template>
        <template v-else-if="form.type === 'el-select'">
          <el-select value-key="value" v-model="formProps.model[form.key]"  :placeholder="form.placeholder" size="large">
            <el-option
                v-for="item in form.options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </template>
      </el-form-item>
    </el-form>
    <div class="form-btns" v-if="isShowBtns">
      <el-button size="large" @click="cancelSubmit">取消</el-button>
      <el-button size="large" type="primary" @click="save">保存</el-button>
      <el-button size="large" type="success" @click="saveMore" v-if="page === 'add'">{{ saveBtn }}</el-button>
    </div>
  </div>
</template>

<script setup name="Form">
import {
  defineProps, defineEmits, reactive, ref, onMounted,
} from 'vue';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';

const emit = defineEmits(['saveData', 'saveMore','cancelSubmit']);
const rules = reactive({});
const ruleFormRef = ref(null);
const router = useRouter();
const props = defineProps({
  formProps: {
    type: Object,
    default: [],
  },
  saveBtn: {
    type: String,
    default: '',
  },
  page: {
    type: String,
    default: '',
  },
  isShowBtns: {
    type: Boolean,
    default: true,
  },
});
function save() {
  ruleFormRef.value.validate((valid, fields) => {
    if (valid) {
      emit('saveData');
    } else {
      ElMessage.error('请完善相关信息');
    }
  });
}
function cancelSubmit() {
  emit('cancelSubmit');
}
function saveMore() {
  emit('saveMore');
}
props.formProps.formItems.filter((item) => item.rules).forEach((item) => {
  rules[item.key] = item.rules;
});
onMounted(() => {
  ruleFormRef.value?.resetFields();
});
</script>

<style scoped lang="css">
.form-container {
  height: 100%;
  background-color: var(--el-bg-color) !important;
}
.form-btns {
  display: flex;
  justify-content: center;
}
</style>
